<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2019/11/29
 * Time: 15:23
 */

namespace app\api\controller\deliver\v1;

use app\api\model\Approval;
use app\api\model\Common;
use app\api\model\OrderDeliveryManagerModel;
use app\api\model\Reimbursement;
use think\Controller;
use think\Request;
use app\api\model\Authority;

class ActionCheck extends Controller
{
    protected $us;
    
    public function _initialize()
    {
        $this->us = Authority::check(1);
    }
    
    public function index(Reimbursement $reimbursement, Common $common)
    {
        $data         = Authority::param(['orderId']);
        $description  = \db('user_config', config('database.zong'))->where('key', 'action_check')->value('value');
        $action_check = json_decode($description, true);
        
        $orderFind = db('order')
            ->field('order_times.first_through_time as through,order_times.first_clock_time as clockTime,order_times.envelopes_first_time as envelopes,order_times.signing_time as signing,startup.handover,GROUP_CONCAT(startup_handover.img_url) as handovers,startup.sta_time,startup.up_time,GROUP_CONCAT(DISTINCT capital.capital_id) as capital,GROUP_CONCAT(DISTINCT app_user_order_capital.id) as appUserOrder,order.start_time as startTime,order.acceptance_time,order.cleared_time,order.settlement_time')
            ->join('order_times', 'order_times.order_id=order.order_id', 'left')
            ->join('startup', 'startup.orders_id=order.order_id', 'left')
            ->join('capital', 'capital.ordesr_id=order.order_id and capital.types=1  and capital.enable=1 and capital.agency=0', 'left')
            ->join('app_user_order_capital', 'app_user_order_capital.order_id=order.order_id and app_user_order_capital.deleted_at is null', 'left')
            ->join('startup_handover', 'startup.startup_id=startup_handover.startup_id', 'left')
            ->where('order.order_id', $data['orderId'])
            ->group('order.order_id')
            ->select();
        
        $reimbursementList = $reimbursement->QuantityOfMainMaterialsPurchasedOnBehalf($data['orderId']);
        $inTotal           = 0;
        $nodeList          = 0;
        if (!empty($orderFind)) {
            if (!empty($orderFind[0]['capital'])) {
                $Node = $common->ConstructionNode($orderFind[0]['capital'], $data['orderId']);
                if ($Node['auxiliary_interactive'] == $Node['inTotal']) {
                    $inTotal = 1;
                }
                
                if ($Node['auxiliary_interactive'] == $Node['reviewed']) {
                    $nodeList = 1;
                }
            }
            
        }
        foreach ($action_check as $k => $list) {
            $action_check[$k]['choice'] = null;
            if ($list['choice']) {
                foreach ($list['choice'] as $s => $item) {
                    $action_check[$k]['choice'][$s]['state']     = 0;
                    $action_check[$k]['choice'][$s]['title']     = $item['title'];
                    $action_check[$k]['choice'][$s]['necessary'] = $item['necessary'];
                    $action_check[$k]['choice'][$s]['content']   = $item['content'];
                    if ($item['type'] == 1 && (!empty($orderFind[0]['handover']) || !empty($orderFind[0]['handovers']))) {
                        $action_check[$k]['choice'][$s]['state'] = 1;
                        $action_check[$k]['choice'][$s]['title'] = $item['title'];
                    } elseif ($item['type'] == 2 && (!empty($orderFind[0]['sta_time']) && !empty($orderFind[0]['up_time']))) {
                        $action_check[$k]['choice'][$s]['state'] = 1;
                        $action_check[$k]['choice'][$s]['title'] = $item['title'];
                    } elseif ($item['type'] == 3 && !empty($orderFind) && (count(explode(',', $orderFind[0]['capital'])) <= count(explode(',', $orderFind[0]['appUserOrder'])))) {
                        $action_check[$k]['choice'][$s]['state'] = 1;
                        $action_check[$k]['choice'][$s]['title'] = $item['title'];
                    } elseif ($item['type'] == 4 && !empty($orderFind[0]['startTime'])) {
                        $action_check[$k]['choice'][$s]['state'] = 1;
                        $action_check[$k]['choice'][$s]['title'] = $item['title'];
                    } elseif ($item['type'] == 5) {
                        $action_check[$k]['choice'][$s]['state'] = $inTotal;
                        $action_check[$k]['choice'][$s]['title'] = $item['title'];
                    } elseif ($item['type'] == 6) {
                        $action_check[$k]['choice'][$s]['state'] = $nodeList;
                        $action_check[$k]['choice'][$s]['title'] = $item['title'];
                    }
                }
            }
            
            unset($action_check[$k]['pid']);
        }
        
        foreach ($action_check as $k => $list) {
            switch ($list['type']) {
                case 1:
                    $action_check[$k]['state'] = empty($orderFind[0]['through']) ? 0 : 1;
                    break;
                case 2:
                    $action_check[$k]['state'] = empty($orderFind[0]['clockTime']) ? 0 : 1;
                    break;
                case 3 :
                case 4:
                    $action_check[$k]['state'] = empty($orderFind[0]['envelopes']) ? 0 : 1;
                    break;
//                case 4:
//                    $action_check[$k]['state'] = empty($orderFind[0]['envelopes']) ? 0 : 1;
//                    break;
                case 5:
                    $action_check[$k]['state'] = empty($orderFind[0]['signing']) ? 0 : 1;
                    break;
                case 6:
                    $action_check[$k]['state'] = in_array(0, array_column($list['choice'], 'state')) ? 0 : 1;
                    break;
                case 7:
                    $action_check[$k]['state'] = empty($orderFind[0]['acceptance_time']) ? 0 : 1;
                    break;
                case 8:
                    $action_check[$k]['state']    = 1;
                    $action_check[$k]['showWord'] = empty($reimbursementList[0]['manReimbursement']) ? "未操作" : '已提交' . $reimbursementList[0]['manReimbursement'] . "次";
                    break;
                case 9:
                    $action_check[$k]['state']    = 1;
                    $action_check[$k]['showWord'] = empty($reimbursementList[0]['reimbursementAnge']) ? "未操作" : '已提交' . $reimbursementList[0]['reimbursementAnge'] . "次";
                    break;
                case 10:
                    $action_check[$k]['state']    = 1;
                    $action_check[$k]['showWord'] = empty($reimbursementList[0]['cooperation']) ? "未操作" : '已提交' . $reimbursementList[0]['cooperation'] . "次";
                    break;
                case 11:
                    $action_check[$k]['state'] = empty($orderFind[0]['cleared_time']) ? 0 : 1;
                    break;
                case 12:
                    $action_check[$k]['state'] = empty($orderFind[0]['settlement_time']) ? 0 : 1;
                    break;
                
                
            }
        }
        r_date($action_check, 200);
        
    }/*
     * 订单特权及超限申请记录表
     */
    public function OverLimitApplication(Approval $approval,OrderDeliveryManagerModel $deliveryManagerModel)
    {
        $data         = Authority::param(['orderId', 'relationId', 'money', 'explain', 'picture', 'type']);
        $param        = Request::instance()->post();
        $FieldExplain = Common::approvalFieldExplain($data['type'], $param['typeOfTransfinite']);
        $state        = db('order')->where('order_id', $data['orderId'])->field('cleared_time,settlement_time')->find();
        $IsStartupDelivere=$deliveryManagerModel->IsStartupDeliverer($data['orderId'],$this->us['user_id'],'');
        if(!empty($IsStartupDelivere)){
            r_date(null, 300, '请接单后再操作');
        }
        if ($FieldExplain['type'] == 0) {
            r_date(null, 300, "未定义type类型");
        }
        $cost=isset($param['cost'])?$param['cost']:0;
        $data['money']=$data['money']+$cost;
        $order_aggregate = \db('order_aggregate')->where('order_id', $data['orderId'])->find();
        if ($data['type'] == 3) {
            if ($param['typeOfTransfinite'] == 2 && !empty($state['settlement_time'])) {
                r_date(null, 300, '代购已经结算，无法申请优惠');
            }
            if ($param['typeOfTransfinite'] == 1 && !empty($state['cleared_time'])) {
                r_date(null, 300, '主合同已经结算，无法申请优惠');
            }
            if ($param['typeOfTransfinite'] == 1) {
                if ($order_aggregate['main_price'] < $data['money']) {
                    r_date(null, 300, "优惠金额不能大于主合同总金额");
                }
            }
            if ($param['typeOfTransfinite'] == 2) {
                if ($order_aggregate['agent_price'] < $data['money']) {
                    r_date(null, 300, "优惠金额不能大于代购合同总金额");
                }
            }
        }
        if ($data['money'] == 0) {
            r_date(null, 300, "申请金额不能为0");
        }
        $order = \db('approval_record', config('database.zong'))->where(['type' => $FieldExplain['type'], 'order_id' => $data['orderId'], 'relation_id' => $data['relationId'], 'status' => 0])->select();
        if (!empty($order)) {
            r_date(null, 300, "当前已有超限审批未审核");
        }
        if (empty($data['relationId'])) {
            r_date(null, 300, "参数错误");
        }
        $picture     = json_decode($data['picture'], true);
        $description = \db('approval_record', config('database.zong'))->insertGetId([
            'city_id' => config('cityId'),
            'order_id' => $data['orderId'],
            'relation_id' => $data['relationId'],
            'type' => $FieldExplain['type'],
            'change_value' => $data['money'],
            'status' => 0,
            'created_time' => time(),
            'explains' => $data['explain'],
            'picture' => !empty($picture) ? serialize($picture) : '',
        ]);
        $approval->Reimbursement($description, '店长' . $this->us['username'] . $FieldExplain['title'], $this->us['username'], 12);
        r_date(null, 200);
    }
    
    public function OverLimitApplicationRecord()
    {
        $data                       = Authority::param(['orderId', 'relationId', 'type']);
        $approval_record            = \db('approval_record', config('database.zong'))
            ->field('approval_record.type,approval_record.change_value,approval_record.explains,approval_record.picture,bi_user.username,FROM_UNIXTIME(approval_record.created_time,"%Y-%m-%d %H:%i:%s") as createdTime')
            ->join('approval', 'approval.relation_id=approval_record.id and approval.type=12', 'left')
            ->join('bi_user', 'bi_user.user_id=approval.nxt_id', 'left')
            ->order('approval_record.id desc')
            ->where(['approval_record.order_id' => $data['orderId'], 'approval_record.type' => $data['type'], 'approval_record.relation_id' => $data['relationId']])
            ->find();
        $approval_record['picture'] = empty($approval_record['picture']) ? null : unserialize($approval_record['picture']);
        $approval_record['explain'] = $approval_record['explains'];
        switch ($approval_record['type']) {
            case 1:
                $title = "特权订单";
                $type  = 1;
                break;
            case 2:
                $title = "主合同增减优惠金额";
                $type  = 2;
                break;
            case 3 :
                $title = "代购合同增减优惠金额";
                $type  = 3;
            case 4:
                $title = "主合同增减管理费金额";
                $type  = 4;
                break;
            case 5:
                $title = "代购合同增减管理费金额";
                $type  = 5;
                break;
            case 6:
                $title = "清单总人工费增减金额";
                $type  = 6;
                break;
            case 7:
                $title = "主合同超限报销占合同金额比例";
                $type  = 7;
                break;
            case 8:
                $title = "代购超限请款占合同金额比例";
                $type  = 8;
                break;
            case 9:
                $title = "清单总人工费增减金额[协作师傅]";
                $type  = 9;
                break;
            case 10:
                $title = "超工期申请";
                $type  = 10;
                break;
        }
        $approval_record['type'] = $title;
        r_date($approval_record, 200);
        
    }
    
}